
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>SpringBoot中SPI机制 - 交互式测验</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        
        body {
          font-family: 'Noto Sans SC', sans-serif;
          background-color: #f4f7f9;
          color: #333;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          padding: 20px;
          box-sizing: border-box;
        }
        
        .main-wrapper {
            position: relative;
            width: 100%;
            max-width: 900px; /* Wider to accommodate buttons */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .quiz-container {
          background-color: #ffffff;
          border-radius: 16px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
          width: 100%;
          max-width: 700px;
          overflow: hidden;
          z-index: 10;
        }

        .quiz-header {
          background-color: #4a90e2;
          color: white;
          padding: 20px 30px;
          text-align: center;
        }

        .quiz-header h1 {
          margin: 0;
          font-size: 24px;
          font-weight: 700;
        }
        
        .quiz-header p {
            margin: 5px 0 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .quiz-body {
          padding: 30px;
        }

        .progress-bar {
            display: none; /* 隐藏进度条 */
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 5px;
            height: 10px;
            margin-bottom: 20px;
        }

        #progress-indicator {
            height: 100%;
            width: 0%;
            background-color: #4caf50;
            border-radius: 5px;
            transition: width 0.3s ease;
        }

        #question-container {
          margin-bottom: 20px;
        }

        #question-text {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.6;
          margin-bottom: 25px;
        }

        .options-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .option-item {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .option-item:hover {
          background-color: #e9ecef;
        }
        
        .option-item.selected {
            background-color: #d1e7fd;
            border-color: #4a90e2;
        }

        .quiz-footer {
          padding: 20px 30px;
          display: flex;
          justify-content: space-between; /* 将按钮分布在两侧 */
          align-items: center;
          min-height: 65px; /* Reserve space */
        }

        .nav-btn {
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 20px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease, transform 0.2s ease;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        #next-btn {
            background-color: #28a745;
        }

        .nav-btn:hover {
          background-color: #357abd;
          transform: scale(1.05);
        }
        
        .nav-btn:disabled {
            background-color: #a0c3e8;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #result-container {
            border-top: 1px solid #eee;
        }
        
        .result-box {
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-box.correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-box.incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .result-box h3 {
            margin-top: 0;
        }

        .explanation-text {
            margin-top: 15px;
            line-height: 1.7;
        }
        
        .source-text {
            font-style: italic;
            font-size: 14px;
            margin-top: 15px;
            color: #555;
        }

        
        .final-score-container {
            padding: 40px;
            text-align: center;
        }
        .final-score-container h2 {
            margin-top: 0;
            margin-bottom: 30px;
        }
        .score-summary {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }
        .score-card {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            width: 180px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
        .score-card h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: 500;
            color: #555;
        }
        .score-card p {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }
        .score-details table {
            width: 100%;
            font-size: 16px;
        }
        .score-details td {
            padding: 4px 0;
        }
        .score-details td:last-child {
            text-align: right;
            font-weight: 700;
        }
        .report-actions button {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 12px 25px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
            transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
        }
        .report-actions button:hover {
            background-color: #f1f1f1;
            border-color: #bbb;
            transform: translateY(-2px);
        }
        .report-actions button.primary {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .report-actions button.primary:hover {
            background-color: #218838;
        }
        
        .hint-container {
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #006064;
            font-size: 15px;
            line-height: 1.6;
            display: none; /* 默认隐藏 */
        }
      </style>
    </head>
    <body>
      <div class="main-wrapper">
          <div class="quiz-container">
            <div class="quiz-header">
              <h1>SpringBoot中SPI机制 - 交互式测验</h1>
              <p>检验你对文档内容的理解程度</p>
            </div>
            <div id="quiz-content">
                <div class="quiz-body">
                    <div class="progress-bar">
                        <div id="progress-indicator"></div>
                    </div>
                    <div id="question-container">
                      <p id="question-text"></p>
                      <ul class="options-list" id="options-list"></ul>
                    </div>
                    <div id="result-container"></div>
                    <div id="hint-container" class="hint-container"></div>
                </div>
                <div class="quiz-footer" id="quiz-footer">
                  <button id="prev-btn" class="nav-btn">上一题</button>
                  <button id="hint-btn" class="nav-btn" style="background-color: #ffc107; color: #333; box-shadow: 0 4px 12px rgba(255,193,7,0.3);">提示</button>
                  <button id="next-btn" class="nav-btn">下一题</button>
                </div>
            </div>
          </div>
      </div>

      <script>
        const quizData = [
  {
    "question": "根据文档，SPI（Service Provider Interface）和 API（Application Programming Interface）最核心的区别是什么？",
    "options": [
      "SPI 是框架提供给扩展方实现的接口，控制权在框架方",
      "API 是框架等待被动调用的接口，控制权在调用方",
      "SPI 和 API 在控制权归属上没有本质区别，只是命名不同",
      "API 是服务方提供给调用方使用的接口，但控制权在服务方"
    ],
    "correctAnswerIndex": 0,
    "explanation": "API 是调用方主动调用服务方提供的接口，控制权在调用方。而 SPI 则相反，是框架定义接口，由扩展方（服务提供方）来实现，框架在运行时动态发现并加载这些实现，控制权在框架方。这是一种“控制反转”的思想。",
    "source": "文档中「一、SPI 机制的基本概念」部分的「3. SPI 与 API 的区别与联系」",
    "hint": "文档中提到：简单理解：API 是'我'主动调用你，SPI 是'我'等着被调用。"
  },
  {
    "question": "JDK 原生的 SPI 机制依赖于哪个核心类来加载服务实现，并且配置文件应该放在哪个目录下？",
    "options": [
      "SpringFactoriesLoader 和 META-INF/spring.factories 目录",
      "ClassLoader 和 META-INF/services.properties 文件",
      "java.util.ServiceLoader 和 META-INF/services 目录",
      "java.util.ServiceLoader 和 resources/config 目录"
    ],
    "correctAnswerIndex": 2,
    "explanation": "JDK 从1.6版本开始提供的原生SPI机制，其核心加载器是 `java.util.ServiceLoader`。它通过扫描 classpath 下所有JAR包的 `META-INF/services/` 目录，并读取以接口全限定名命名的文件来找到具体的实现类。",
    "source": "文档中「一、SPI 机制的基本概念」部分的「2. JDK 原生 SPI 的实现原理」",
    "hint": "文档中列出了使用JDK原生SPI的步骤，其中第三步和第五步明确了文件位置和加载类。"
  },
  {
    "question": "与JDK原生SPI不同，SpringBoot实现了一套增强的SPI机制。其核心加载类和默认配置文件名分别是什么？",
    "options": [
      "ServiceLoader, META-INF/services",
      "SpringFactoriesLoader, META-INF/spring.factories",
      "AutoConfigurationLoader, application.properties",
      "BeanDefinitionLoader, META-INF/beans.xml"
    ],
    "correctAnswerIndex": 1,
    "explanation": "SpringBoot的SPI核心类是`SpringFactoriesLoader`，它专门负责加载所有JAR包中`META-INF/`目录下的`spring.factories`文件。这个文件定义了各种扩展点的实现，是SpringBoot自动配置等功能的基础。",
    "source": "文档中「二、SpringBoot SPI 机制的实现原理」部分的「2. SpringFactoriesLoader 详解」",
    "hint": "文档第二章节的标题就提到了SpringBoot SPI的核心实现，并详细解释了与之相关的配置文件。"
  },
  {
    "question": "相比于JDK原生的SPI，SpringBoot的SPI机制提供了多项增强功能。以下哪项是文档中提到的增强点之一？",
    "options": [
      "只允许每个接口有一个实现类，以避免冲突",
      "提供了缓存机制以优化性能，并支持按条件加载",
      "强制使用XML文件进行配置，以提高可读性",
      "移除了对接口的依赖，可以直接加载具体类"
    ],
    "correctAnswerIndex": 1,
    "explanation": "文档中明确列出了SpringBoot对JDK SPI的几大增强点，包括：支持key-value形式的配置、支持同一接口多个实现类的排序、支持按条件加载以及提供缓存优化。这些增强使得SpringBoot的扩展机制更加灵活和高效。",
    "source": "文档中「二、SpringBoot SPI 机制的实现原理」部分的「1. SpringBoot 对 JDK SPI 的增强」",
    "hint": "在文档的第二部分，有一个列表专门总结了SpringBoot对JDK SPI的增强功能。"
  },
  {
    "question": "在SpringBoot中，哪个注解是触发自动配置流程的关键，它通过导入哪个类来利用SPI机制加载配置？",
    "options": [
      "@ComponentScan，它导入 ComponentScanner 来扫描组件",
      "@Configuration，它通过 BeanFactory 来查找配置类",
      "@SpringBootApplication，它直接调用 SpringFactoriesLoader",
      "@EnableAutoConfiguration，它导入 AutoConfigurationImportSelector 来加载配置"
    ],
    "correctAnswerIndex": 3,
    "explanation": "SpringBoot的自动配置由`@EnableAutoConfiguration`注解启动。该注解内部通过`@Import(AutoConfigurationImportSelector.class)`引入了`AutoConfigurationImportSelector`，这个选择器类进而使用`SpringFactoriesLoader`从各个`spring.factories`文件中加载所有自动配置类的名称，从而启动整个自动配置过程。",
    "source": "文档中「三、SpringBoot 自动配置中的 SPI 应用」部分的「2. EnableAutoConfiguration 注解背后的 SPI 机制」",
    "hint": "文档中的代码示例展示了`@EnableAutoConfiguration`注解的定义，其中`@Import`注解是关键线索。"
  },
  {
    "question": "如果你正在开发一个starter，并希望为你的功能创建一个自定义的自动配置类，你应该如何让SpringBoot发现并加载它？",
    "options": [
      "只需在你的类上添加`@Configuration`注解，SpringBoot会自动扫描到它",
      "修改SpringBoot核心依赖的`spring.factories`文件，加入你的配置类",
      "在项目的`src/main/resources/META-INF`目录下创建`spring.factories`文件，并将你的配置类添加到`org.springframework.boot.autoconfigure.EnableAutoConfiguration`键下",
      "在`application.properties`中使用`spring.autoconfigure.include`属性指定你的配置类"
    ],
    "correctAnswerIndex": 2,
    "explanation": "要让SpringBoot的自动配置机制发现你的自定义配置，标准的做法是在你的项目（通常是starter）的`src/main/resources/META-INF/`目录下创建一个`spring.factories`文件。然后，在该文件中，将你的自动配置类的全限定名作为值，赋给`org.springframework.boot.autoconfigure.EnableAutoConfiguration`这个键。",
    "source": "文档中「四、基于 SPI 开发 SpringBoot 扩展」部分的「1. 创建自己的 spring.factories 文件」",
    "hint": "文档第四部分详细介绍了如何开发一个SpringBoot扩展，第一步就是关于如何让SpringBoot发现你的配置。"
  },
  {
    "question": "SpringBoot如何实现在特定条件（例如classpath下存在某个类）下才加载对应的自动配置？",
    "options": [
      "通过在`spring.factories`文件中添加特殊的条件标记",
      "在自动配置类中使用`if-else`语句手动检查环境",
      "依赖XML配置文件中的`<if-exists>`标签",
      "结合使用SPI机制和`@ConditionalOnClass`等条件注解"
    ],
    "correctAnswerIndex": 3,
    "explanation": "SpringBoot将SPI机制与条件注解（如@ConditionalOnClass, @ConditionalOnProperty等）紧密结合，实现了高度灵活的组件加载。自动配置类虽然在`spring.factories`中被列出，但只有当其上的条件注解所定义的条件全部满足时，这个配置类才会被真正地实例化并注册到Spring容器中。",
    "source": "文档中「五、SpringBoot SPI 机制的高级特性」部分的「1. 条件化装配与 SPI」",
    "hint": "文档中给出了`RedisAutoConfiguration`的例子，它使用了一个注解来判断`RedisOperations.class`是否存在。"
  },
  {
    "question": "当你的自动配置类不生效时，文档推荐的首要排查方法是什么？",
    "options": [
      "在`application.properties`中设置`debug=true`以启用自动配置报告",
      "在IDE中对`SpringFactoriesLoader`类设置断点进行调试",
      "将日志级别调整为TRACE，并分析所有输出",
      "检查操作系统的环境变量是否正确配置"
    ],
    "correctAnswerIndex": 0,
    "explanation": "为了方便开发者诊断自动配置问题，SpringBoot提供了一个内置的自动配置报告功能。通过在`application.properties`或`application.yml`中设置`debug=true`，应用启动时会打印一份详细的报告，清晰地列出哪些自动配置被匹配（生效），哪些没有被匹配（未生效）以及具体原因，这是排查此类问题的首选方法。",
    "source": "文档中「四、基于 SPI 开发 SpringBoot 扩展」部分的「4. 调试与排错技巧」",
    "hint": "文档的“调试与排错技巧”一节给出了一个非常直接的配置项来获取诊断信息。"
  }
];
        console.log("Quiz Data:", JSON.parse(JSON.stringify(quizData))); // 添加这行用于调试，以可展开的JSON格式输出
        
        let currentQuestionIndex = 0;
        let score = 0;
        // 存储每个问题的回答状态
        const userAnswers = new Array(quizData.length).fill(null); 

        const questionTextEl = document.getElementById('question-text');
        const optionsListEl = document.getElementById('options-list');
        const resultContainerEl = document.getElementById('result-container');
        const quizContentEl = document.getElementById('quiz-content');
        const progressIndicatorEl = document.getElementById('progress-indicator');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const hintBtn = document.getElementById('hint-btn');
        const hintContainerEl = document.getElementById('hint-container');

        function loadQuestion() {
          resultContainerEl.innerHTML = '';
          optionsListEl.innerHTML = '';
          hintContainerEl.style.display = 'none'; // 隐藏提示
          
          if (currentQuestionIndex >= quizData.length) {
            showFinalScore();
            return;
          }

          updateProgress();

          const currentQuestion = quizData[currentQuestionIndex];
          questionTextEl.textContent = `(${currentQuestionIndex + 1}/${quizData.length}) ${currentQuestion.question}`;
          
          currentQuestion.options.forEach((optionText, index) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.textContent = optionText;
            li.dataset.index = index; // Store index in a data attribute
            // 如果这道题已经回答过，恢复状态
            if (userAnswers[currentQuestionIndex] !== null) {
                if (index === userAnswers[currentQuestionIndex]) {
                    li.classList.add('selected');
                }
            }
            optionsListEl.appendChild(li);
          });

          // 如果已经回答过，直接显示结果
          if (userAnswers[currentQuestionIndex] !== null) {
              const isCorrect = userAnswers[currentQuestionIndex] === currentQuestion.correctAnswerIndex;
              showResult(isCorrect, currentQuestion);
          }
          
          updateNavigationButtons();
          updateProgress();
        }

        function selectOption(optionIndex) {
            userAnswers[currentQuestionIndex] = optionIndex;
            const currentQuestion = quizData[currentQuestionIndex];
            const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;

            // 重新计算分数
            score = userAnswers.reduce((acc, answer, index) => {
                return answer === quizData[index].correctAnswerIndex ? acc + 1 : acc;
            }, 0);

            showResult(isCorrect, currentQuestion);
            updateNavigationButtons();
        }
        
        function updateProgress() {
            const answeredQuestions = userAnswers.filter(answer => answer !== null).length;
            const progressPercentage = (answeredQuestions / quizData.length) * 100;
            progressIndicatorEl.style.width = `${progressPercentage}%`;
        }
        
        function updateNavigationButtons() {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            hintBtn.style.display = 'block'; // 显示提示按钮

            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = false; // 最后一题时，下一题按钮不禁用，而是用于显示报告
            nextBtn.textContent = (currentQuestionIndex === quizData.length - 1) ? '查看报告' : '下一题';
            
            // 如果当前问题没有提示，则禁用提示按钮并隐藏提示内容
            if (!quizData[currentQuestionIndex].hint) {
                hintBtn.disabled = true;
                hintContainerEl.style.display = 'none';
                hintContainerEl.textContent = ''; // 清除旧的提示内容
            } else {
                hintBtn.disabled = false;
            }
        }

        function showResult(isCorrect, questionData) {
            resultContainerEl.innerHTML = ''; // 清空之前的结果
            const resultBox = document.createElement('div');
            resultBox.className = `result-box ${isCorrect ? 'correct' : 'incorrect'}`;
            
            let html = `<h3>${isCorrect ? '回答正确！' : '回答错误'}</h3>`;
            if (!isCorrect) {
                html += `<p><strong>正确答案是：</strong> ${questionData.options[questionData.correctAnswerIndex]}</p>`;
            }
            html += `<div class="explanation-text">${questionData.explanation}</div>`;
            html += `<div class="source-text">来源: ${questionData.source}</div>`;
            
            resultBox.innerHTML = html;
            resultContainerEl.appendChild(resultBox);

            // 禁用所有选项的点击事件，并高亮正确/错误答案
            Array.from(optionsListEl.children).forEach((child, index) => {
                child.style.pointerEvents = 'none';
                // 高亮正确答案
                if (index === questionData.correctAnswerIndex) {
                    child.classList.add('correct'); // 需要添加CSS样式
                    child.style.backgroundColor = '#d4edda';
                    child.style.borderColor = '#c3e6cb';
                }
                // 如果选错了，高亮错误选项
                if (!isCorrect && index === userAnswers[currentQuestionIndex]) {
                    child.classList.add('incorrect'); // 需要添加CSS样式
                    child.style.backgroundColor = '#f8d7da';
                    child.style.borderColor = '#f5c6cb';
                }
            });
        }

        function goToNextQuestion() {
            if (currentQuestionIndex < quizData.length - 1) {
                currentQuestionIndex++;
                loadQuestion();
            } else {
                showFinalScore();
            }
        }

        function goToPreviousQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion();
            }
        }
        
        function showHint() {
            const currentQuestion = quizData[currentQuestionIndex];
            if (currentQuestion.hint) {
                hintContainerEl.textContent = currentQuestion.hint;
                hintContainerEl.style.display = 'block';
            } else {
                hintContainerEl.style.display = 'none';
            }
        }

        function showFinalScore() {
            document.querySelector('.quiz-body').style.display = 'none';
            document.getElementById('quiz-footer').style.display = 'none';

            const correctCount = score;
            const totalQuestions = quizData.length;
            const answeredCount = userAnswers.filter(a => a !== null).length;
            const wrongCount = answeredCount - correctCount;
            const skippedCount = totalQuestions - answeredCount;
            const accuracy = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
            const errorRate = totalQuestions > 0 ? Math.round((wrongCount / totalQuestions) * 100) : 0;

            const finalScoreHtml =
                '<div class="final-score-container">' +
                '<h2>答题报告</h2>' +
                '<div class="score-summary">' +
                '<div class="score-card">' +
                '<h3>得分</h3>' +
                '<p>' + correctCount + ' / ' + totalQuestions + '</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>正确率</h3>' +
                '<p>' + accuracy + '%</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>错误率</h3>' +
                '<p>' + errorRate + '%</p>' +
                '</div>' +
                '<div class="score-card score-details">' +
                '<table>' +
                '<tr><td>正确</td><td>' + correctCount + '</td></tr>' +
                '<tr><td>错误</td><td>' + wrongCount + '</td></tr>' +
                '<tr><td>未答</td><td>' + skippedCount + '</td></tr>' +
                '</table>' +
                '</div>' +
                '</div>' +
                '<div class="report-actions">' +
                '<button id="review-btn">回顾测验</button>' +
                '<button class="primary" onclick="location.reload()">再试一次</button>' +
                '</div>' +
                '</div>';

            let reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }
            quizContentEl.insertAdjacentHTML('beforeend', finalScoreHtml);
            document.getElementById('review-btn').addEventListener('click', reviewQuiz);
        }

        function reviewQuiz() {
            const reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }

            document.querySelector('.quiz-body').style.display = 'block';
            document.getElementById('quiz-footer').style.display = 'flex';
            
            currentQuestionIndex = 0;
            loadQuestion();
            updateNavigationButtons(); // Ensure nav buttons are correctly displayed
        }

        // Event Delegation for options
        optionsListEl.addEventListener('click', (event) => {
            if (event.target && event.target.matches('li.option-item')) {
                // Check if the question has already been answered
                if (userAnswers[currentQuestionIndex] === null) {
                    const selectedIndex = parseInt(event.target.dataset.index, 10);
                    selectOption(selectedIndex);
                }
            }
        });

        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        hintBtn.addEventListener('click', showHint);
        
        // 初始加载
        loadQuestion();
      </script>
    </body>
    </html>
  